<script setup>
import {
  getPriceList,
  packageInfo,
  getalipayPackageInfo,
  getPayWechtResultApi,
  getPayMuYunResultApi
} from '@/apis/pay';
import router from '@/router';
import { useI18nStore, useToastStore } from '@/stores/index';

const timenum = ref(20);

const toastStore = useToastStore();
const timer = ref(null);
const i18nStore = useI18nStore();
const show = ref(true);
const CurrentPaymentSize = ref('');
const paymentMethod = ref('');
const paymentMoths = ref('');
const paymentSize = ref('');
const price = ref('');
const qrcode = ref('');
const payList = ref([]);
const loading = ref(false);

const extractNumber = (str) => {
  const matches = str.match(/[\d.]+/g);
  return matches
    ? parseFloat(matches[0]) + i18nStore.translate('count')
    : 0 + i18nStore.translate('count');
};

const setpaymentMethod = async (method) => {
  timer.value && clearInterval(timer.value);
  paymentMethod.value = method;
  const payItem = payList.value.filter(
    (item) =>
      item.size == CurrentPaymentSize.value && paymentMoths.value == item.months
  )[0];
  loading.value = true;
  let res;
  timenum.value = 20;

  if (method == 'alipay_qr') {
    res = await getalipayPackageInfo({
      id: payItem.id,
      channelCode: method,
      returnUrl: 'okpan.com'
    });
    timer.value = setInterval(async () => {
      timenum.value--;
      if (timenum.value == 0) {
        clearInterval(timer.value);
        loading.value = true;
        toastStore.showToast({
          severity: 'error',
          summary: i18nStore.translate('支付超时'),
          detail: '',
          life: 2000
        });
        return;
      }
      const result = await getPayMuYunResultApi({ orderid: res.data.orderid });
      if (result.data.status == '10') {
        clearInterval(timer.value);
        show.value = false;
        router.push('/userInfo');
        toastStore.showToast({
          severity: 'success',
          summary: i18nStore.translate('支付成功'),
          detail: '',
          life: 2000
        });
      }
    }, 3000);
    // 提取 qrcode 中的参数
    const urlParams = new URLSearchParams(new URL(res.data.url).search);
    const actualPaymentUrl = decodeURIComponent(urlParams.get('qrcode'));
    res.data.displayContent = actualPaymentUrl;
  } else {
    res = await packageInfo({
      id: payItem.id,
      channelCode: method
    });
    timer.value = setInterval(async () => {
      timenum.value--;
      if (timenum.value == 0) {
        clearInterval(timer.value);
        loading.value = true;
        toastStore.showToast({
          severity: 'error',
          summary: i18nStore.translate('支付超时'),
          detail: '',
          life: 2000
        });
        return;
      }
      const result = await getPayWechtResultApi({ id: res.data.id });
      if (result.data.status == '10') {
        clearInterval(timer.value);
        show.value = false;
        router.push('/userInfo');
        toastStore.showToast({
          severity: 'success',
          summary: i18nStore.translate('支付成功'),
          detail: '',
          life: 2000
        });
      }
    }, 3000);
  }

  loading.value = false;
  qrcode.value = res.data.displayContent;
};

const setCurrentPaymentSize = (size) => {
  CurrentPaymentSize.value = size;
  const item = payList.value.filter(
    (item) => item.size == size && item.type == prop.type
  )[0];
  setPaymentMoths(item);
};

const setPaymentMoths = (item) => {
  paymentMoths.value = item.months;
  paymentSize.value = item.size;
  price.value = item.price;
  closeData();
};

const closeData = () => {
  qrcode.value = '';
  paymentMethod.value = '';
};

const popup = ref(null);

const Shut = () => {
  if (timer.value) {
    clearInterval(timer.value);
  }
  show.value = false;
};
const prop = defineProps({
  type: {
    type: String
  }
});
onMounted(async () => {
  const result = await getPriceList({ pageNo: 1, pageSize: 100 });
  payList.value = result.data;
  const size = payList.value.filter((item) => item.type == prop.type)[0].size;
  setCurrentPaymentSize(size);
  document.addEventListener('click', closePopup);
  console.log(prop.type);
});

onBeforeUnmount(() => {
  // 在组件卸载之前，移除事件监听
  document.removeEventListener('click', closePopup);
});

// 点击外部关闭弹出框
const closePopup = (event) => {
  if (popup.value && !popup.value.contains(event.target)) {
    Shut();
  }
};

const payListSize = computed(() => {
  const typeList = payList.value.filter((item) => item.type == prop.type);
  return Array.from(
    new Map(typeList.map((item) => [item.size, item])).values()
  );
});

const payListMoths = computed(() => {
  return payList.value
    .filter((item) => item.type == prop.type && paymentSize.value == item.size)
    .sort((a, b) => a.months - b.months);
});

const paragraphList = computed(() => {
  switch (prop.type) {
    case '1':
      return ['16', '17', '18', '19'];
    case '2':
      return ['6', '7', '8', '9', '10'];
    case '3':
      return ['1', '2', '3', '4', '5'];
    case '4':
      return ['11', '12', '13', '14', '15'];
    default:
      return [];
  }
});
</script>

<template>
  <div
    v-if="show"
    ref="popup"
    class="pay-popup fixed top-2/4 left-2/4 -translate-x-2/4 -translate-y-2/4 mobile:h-full overflow-y-auto w-full pc:w-3/5 px-5 py-5 z-50 border rounded-2xl bg-white mobile:min-h-full dark:bg-dark-background dark:text-white"
  >
    <div class="flex flex-row-reverse justify-between">
      <i :class="`pi pi-times-circle text-xl cursor-pointer`" @click="Shut" />
    </div>
    <div>
      <div class="mb-[20px]">
        <div class="title mb-[20px]">
          {{ i18nStore.translate('choose_file_size') }}
        </div>
        <div class="overflow-x-auto">
          <ul class="flex flex-nowrap">
            <li
              class="flex-shrink-0 w-[200px] h-[200px] border flex flex-col items-center justify-evenly mx-3"
              :key="item.id"
              v-for="item in payListSize"
              :class="{
                'border-[#5CD6C8]': CurrentPaymentSize == item.size
              }"
              @click="setCurrentPaymentSize(item.size)"
            >
              <h3
                class="text-[24px] border-b-[1px] pb-[10px]"
                v-if="prop.type == '1'"
              >
                {{ i18nStore.translate('文件组升级') }}
              </h3>
              <h3
                class="text-[24px] border-b-[1px] pb-[10px]"
                v-if="prop.type == '4'"
              >
                {{ i18nStore.translate('下载点数') }}
              </h3>
              <h3
                class="text-[24px] border-b-[1px] pb-[10px]"
                v-if="prop.type == '3'"
              >
                {{ i18nStore.translate('下载流量包') }}
              </h3>
              <h3
                class="text-[24px] border-b-[1px] pb-[10px]"
                v-if="prop.type == '2'"
              >
                {{ i18nStore.translate('空间扩容') }}
              </h3>
              <div class="text-center">
                <p class="text-[16px] text-[#5CD6C8] font-bold">
                  {{ item.description }}
                </p>
                <p class="text-[14px] text-[#666]">
                  {{ i18nStore.translate('file_speed_unlimited_transfer') }}
                </p>
                <p
                  class="text-[14px] text-[#666]"
                  v-if="CurrentPaymentSize == item.size && prop.type == '1'"
                >
                  {{ i18nStore.translate('Single_file_size') }}
                </p>
                <p
                  class="text-[14px] text-[#666]"
                  v-if="CurrentPaymentSize == item.size"
                >
                  {{
                    prop.type == '4'
                      ? item.size + i18nStore.translate('count')
                      : item.sizeDesc
                  }}{{
                    prop.type == '1' ? i18nStore.translate('file_up_to') : ''
                  }}
                </p>
              </div>
            </li>
          </ul>
        </div>
      </div>
      <div v-if="paragraphList.length">
        <h1 class="font-bold text-[24px] mb-2">
          {{ i18nStore.translate('buy_tips') }}
        </h1>
        <p v-for="(item, index) in paragraphList" :key="item">
          {{ index + 1 }}：{{ i18nStore.translate(`costumbre${item}`) }}
        </p>
      </div>
      <div
        class="mb-[20px] mt-[20px]"
        v-if="prop.type == '1' || prop.type == '2'"
      >
        <div class="title mb-[10px]">
          {{ i18nStore.translate('select_month') }}
        </div>
        <ul class="flex flex-wrap justify-left mb-[10px]">
          <li
            class="w-[120px] h-[50px] border flex flex-col items-center justify-evenly mr-[20px]"
            :class="paymentMoths == item.months ? 'border-[#5CD6C8]' : ''"
            @click="setPaymentMoths(item)"
            v-for="item in payListMoths"
            :key="item.id"
          >
            <div>{{ `${item.months}` + i18nStore.translate('month') }}</div>
          </li>
        </ul>
      </div>
      <div class="mb-[20px]">
        <div class="title mb-[10px]">
          {{ i18nStore.translate('total_amount') }}
        </div>
        <div>
          <p class="font-bold text-[24px]">￥{{ price / 100 }}</p>
        </div>
      </div>
      <div>
        <div class="title mb-[10px]">
          {{ i18nStore.translate('choose_payment_method') }}
        </div>
        <ul class="flex flex-wrap justify-left mb-[10px]">
          <li
            class="w-[120px] h-[50px] border flex flex-col items-center justify-evenly mr-[20px]"
            :class="paymentMethod == 'alipay_qr' ? 'border-[#5CD6C8]' : ''"
            @click="setpaymentMethod('alipay_qr')"
          >
            <div class="w-full h-full flex items-center justify-center">
              <SvgIcon
                name="zhifubao"
                style="width: 80%; height: 80%"
              ></SvgIcon>
            </div>
          </li>
          <li
            class="w-[120px] h-[50px] border flex flex-col items-center justify-evenly"
            :class="paymentMethod == 'wx_native' ? 'border-[#5CD6C8]' : ''"
            @click="setpaymentMethod('wx_native')"
          >
            <div class="w-full h-full flex items-center justify-center">
              <SvgIcon name="weixin" style="width: 80%; height: 80%"></SvgIcon>
            </div>
          </li>
        </ul>
        <div class="w-[150px] h-[150px] ml-12" v-if="qrcode">
          <Qrcode :value="qrcode" :loading="loading" />
        </div>
      </div>
    </div>
  </div>
</template>
